import json
import logging
import sys

import requests

from apps.settingApi.api.timerTask.apiList.logsAdd import add
from apps.settingApi.api.timerTask.model import timerTaskLogModel
from apps.settingApi.switchCase.casePrimaryKey import caseGetPrimaryKeyData
from comm.dateTime import nowData
from comm.openDbConfig import openDbBase


def wmsapiLogin():
    print('wmsPrdt货品基础资料')
    data = {
    "comp_no":"W02",
    "user_id":"ADMIN",
    "password":""
    }
    return

def wmsapiPrdt(db,name):
    print('wmsPrdt货品基础资料')
    logData = {}
    logData['id'] = caseGetPrimaryKeyData()
    logData['status'] = True
    logData['name'] = name
    add(db,logData)
    return

class wmsApiList:
    dbproconfig = openDbBase()
    compno = dbproconfig['COMPNO']
    apiUrl = dbproconfig['wimsUrl']
    usr = dbproconfig['wimsUsername']
    pwd = dbproconfig['wimsPassword']
    apiAdd = dbproconfig['wimsUrl']

    @classmethod
    def getToken(cls):
        import os
        # 当前脚本作为主程序运行时的路径
        if getattr(sys, 'frozen', False):
            entry_point_path = sys.executable
            # print(111,entry_point_path)
        else:
            entry_point_path = sys.modules['__main__'].__file__
            # print(222,entry_point_path)
        entry_point_abs_path  = os.path.dirname(os.path.abspath(entry_point_path))
        # print("入口文件路径:", entry_point_abs_path)
        entry_point_abs_path = entry_point_abs_path + '\\api__init__.txt'
        if os.path.exists(entry_point_abs_path):
            # 文件存在读取文件中的wms token
            with open(entry_point_abs_path, 'r',encoding="utf-8") as file:
                content = file.read()
                try:
                    apiTokenObj = json.loads(content)
                except Exception as e:
                    logging.info('wms读取缓存中的token失败' + repr(e))
                    return None, "wms读取缓存中的token失败" + repr(e)
                # 文件中不存在wms的token则登录
                if "wms" not in apiTokenObj.keys():
                    # print("不存在wms的token")
                    logging.info('不存在wms的token')
                    token, err = cls.login()
                    if err != None:
                        return None, err
                    getToken = {}
                    getToken["token"] = token
                    getToken["time"] = nowData(hour=1)
                    apiTokenObj["wms"] = getToken
                    # 将token写入到文件中
                    with open(entry_point_abs_path, 'w', encoding="utf-8") as file:
                        file.write(json.dumps(apiTokenObj))
                # 判断token是否过期
                if apiTokenObj["wms"]["time"] <=nowData():
                    logging.info('wms的token过期重新登录获取')
                    # token过期重新获取token
                    # print("wms的token过期重新获取token")
                    token, err = cls.login()
                    if err != None:
                        return None, err
                    with open(entry_point_abs_path, 'w', encoding="utf-8") as file:
                        getToken = {}
                        getToken["token"] = token
                        getToken["time"] = nowData(hour=1)
                        apiTokenObj["wms"] = getToken
                        # 将token写入到文件中
                        print(apiTokenObj)
                        file.write(json.dumps(apiTokenObj))
                token = apiTokenObj['wms']["token"]
        else:
            # print("文件不存在")
            logging.info('wms的token文件不存在登录获取token')
            token,err = cls.login()
            if err!=None:
                return None,err
            with open(entry_point_abs_path, 'w',encoding="utf-8") as file:
                getToken = {}
                getToken["token"] = token
                getToken["time"] = nowData(hour=1)
                apiTokenObj = {}
                apiTokenObj["wms"] = getToken
                # 将token写入到文件中
                file.write(json.dumps(apiTokenObj))
        return token,None
    @classmethod
    def login(cls):
        url = cls.apiAdd + "SYS/LOGIN"
        jsonData = {
            "comp_no":cls.compno,
            "user_id":cls.usr,
            "password":cls.pwd
        }
        header = {
            "Content-Type":"application/json"
        }
        r = requests.post(url,json=jsonData,headers=header)
        if r.status_code != 200:
            logging.info('wms登录失败状态码非200')
            return None, '登录接口请求失败'
        resData = r.json()
        if resData['code']!=0:
            logging.info('wms登录失代码' + str(resData['code']) + resData['message'])
            return None,str(resData['code']) + resData['message']
        logging.info('wms token获取成功')
        return resData['token'],None

    @classmethod
    def apiComm(cls,data,url):
        """
        :param data: 表身参数
        :param token: 请求头token
        :param url: 请求接口
        :return:
        """
        url = cls.apiAdd + url
        jsonData = data

        token, err = cls.getToken()
        if err != None:
            return None, err
        header = {
            "Content-Type": "application/json",
            "Authorization": token
        }
        r = requests.post(url, json=jsonData, headers=header)
        if r.status_code != 200:
            return None, '状态码非200新增失败' + r.text
        resData = r.json()
        # print('resData',resData)
        if resData['code'] != 0:
            return None, str(resData['code']) + resData['message']
        return None, None
    # 货品基础资料
    @classmethod
    def addPrdt(cls,data):
        """

        :param data: 表身参数
        :param token: 请求头token
        :return:
        """
        url = cls.apiAdd + "SYS/CreateProduct"
        jsonData = data


        token,err = cls.getToken()
        if err!=None:
            return None,err
        header = {
            "Content-Type": "application/json",
            "Authorization":token
        }
        r = requests.post(url, json=jsonData, headers=header)
        if r.status_code != 200:
            return None, '状态码非200新增失败' + r.text
        resData = r.json()
        if resData['code'] != 0:
            return None, str(resData['code']) + resData['message']
        return None, None

    @classmethod
    def updatePrdt(cls, data):
        """

        :param data: 表身参数
        :param token: 请求头token
        :return:
        """
        url = cls.apiAdd + "SYS/UpdateProduct"
        jsonData = data

        token, err = cls.getToken()
        if err != None:
            return None, err
        header = {
            "Content-Type": "application/json",
            "Authorization": token
        }
        r = requests.post(url, json=jsonData, headers=header)
        if r.status_code != 200:
            return None, '状态码非200新增失败' + r.text
        resData = r.json()
        if resData['code'] != 0:
            return None, str(resData['code']) + resData['message']
        return None, None

    @classmethod
    def mfRkTz(cls, data: dict):
        addData = {}
        entry_order = {}
        entry_order["owner_code"] = "OWNER"
        entry_order["order_type"] = data["order_type"]
        entry_order["oth_task_id"] = data["oth_task_id"]
        entry_order["erp_bil_no"] = data["oth_task_id"]
        entry_order["bil_no"] = data["oth_task_id"]
        entry_order["ref_id"] = data["ref_id"]
        entry_order["entry_order_date"] = data["entry_order_date"]
        entry_order["operate_time"] = data["operate_time"]
        entry_order["request_id"] = data["request_id"]
        entry_order["request_code"] = data["code"]
        entry_order["warehouse_code"] = data["warehouse_code"]
        entry_order["department"] = data["department"]
        entry_order["supplier_code"] = data["supplier_code"]
        entry_order["supplier_name"] = data["supplier_name"]
        entry_order["operator_code"] = data["operator_code"]
        entry_order["expect_start_time"] = data["expect_start_time"]
        entry_order["source_bilno"] = data["source_bilno"]
        entry_order['extend_props'] = {
            "U9CID": data['id'],
            "ALLDH": data['oth_task_id']
        }
        addData["order_lines"] = []
        addData["entry_order"] = entry_order
        return addData

    # 出库通知单表身数据拼接
    @classmethod
    def tfRkTz(cls, code, data: dict, qty_type=True):
        dataList = []
        for index, itm1 in enumerate(data):
            itmData = {}
            itmData['item_code'] = itm1['item_code']
            itmData['item_name'] = itm1['item_name']
            if qty_type == True:
                itmData['qty'] = itm1['qty']
            else:
                itmData['qty'] = -itm1['qty']
            if "batch_code" in itm1.keys():
                itmData['batch_code'] = itm1['batch_code']
            if code in ['pc']:
                itmData['request_itm'] = itm1['itm']
                itmData["source_bilitm"] = itm1['itm']
            else:
                itmData['request_itm'] = index + 1
                itmData["source_bilitm"] = index + 1
            itmData['request_itm'] = index + 1
            # itmData['request_itm'] = itm1["request_itm"]
            itmData["source_bilno"] = itm1["source_bilno"]
            itmData["request_id"] = itm1["request_id"]
            itmData["source_bilid"] = itm1["source_bilid"]
            itmData["request_code"] = itm1["request_code"]
            itmData['extend_props'] = {
                "U9CID": itm1['id']
            }
            dataList.append(itmData)
        return dataList
    # 出库通知单表头数据拼接
    @classmethod
    def mfCkTz(cls,data:dict):
        addData = {}
        entry_order = {}
        entry_order["owner_code"] = "OWNER"
        entry_order["order_type"] = data["order_type"]
        entry_order["oth_task_id"] = data["oth_task_id"]
        entry_order["erp_bil_no"] = data["oth_task_id"]
        entry_order["bil_no"] = data["oth_task_id"]
        entry_order["ref_id"] = data["ref_id"]
        entry_order["delivery_order_date"] = data["delivery_order_date"]
        entry_order["operate_time"] = data["operate_time"]
        entry_order["request_id"] = data["request_id"]
        entry_order["request_code"] = data["code"]
        entry_order["warehouse_code"] = data["warehouse_code"]
        entry_order["department"] = data["department"]
        entry_order["cus_no"] = data["cus_no"]
        entry_order["cus_name"] = data["cus_name"]
        entry_order["operator_code"] = data["operator_code"]
        entry_order["schedule_date"] = data["schedule_date"]
        entry_order["source_bilno"] = data["source_bilno"]
        entry_order['extend_props'] = {
            "U9CID": data['id'],
            "ALLDH": data['oth_task_id']
        }
        addData["delivery_order"] = entry_order
        addData["order_lines"] = []
        return addData

    # 出库通知单表身数据拼接
    @classmethod
    def tfCkTz(cls,code, data: dict, qty_type=True):
        dataList = []
        for index, itm1 in enumerate(data):
            itmData = {}
            itmData['item_code'] = itm1['item_code']
            itmData['item_name'] = itm1['item_name']
            if qty_type == True:
                itmData['qty'] = itm1['qty']
            else:
                itmData['qty'] = -itm1['qty']
            if "batch_code" in itm1.keys():
                itmData['batch_code'] = itm1['batch_code']

            # itmData['request_itm'] = itm1["request_itm"]
            itmData["source_bilno"] = itm1["source_bilno"]
            itmData["request_id"] = itm1["request_id"]
            itmData["source_bilid"] = itm1["source_bilid"]
            itmData["request_code"] = itm1["request_code"]
            # itmData["source_bilitm"] = itm1["source_bilitm"]
            if code in ['sa']:
                itmData['request_itm'] = itm1['itm']
                itmData["source_bilitm"] = itm1['itm']
            else:
                itmData['request_itm'] = index + 1
                itmData["source_bilitm"] = index + 1
            itmData['extend_props'] = {
                "U9CID": str(itm1['id']),
                "U9SOURCEID": itm1['u9sourceid'],
                "U9SOURCENO": itm1['u9sourceno'],
                "U9PROJECTID": itm1['u9projectid'],
                "U9PROJECTNM": itm1['u9projectnm'],
            }
            dataList.append(itmData)
        return dataList

    @classmethod
    def diaoBo(cls,data:dict):
        mf = data['mf']
        tf = data['tf']
        transfer_order = {
            "ref_id": mf["ref_id"],
            "oth_task_id": mf["oth_task_id"],
            "erp_bil_no": mf["oth_task_id"],
            "bil_no": mf["oth_task_id"],
            "generate_mode": "1",
            "transfer_date": mf["operate_time"],
            "owner_code": "OWNER",
            "request_id": mf["request_id"],
            "request_code": mf["code"],
            "warehouse_code1": mf["warehouse_code1"],
            "warehouse_code2": mf["warehouse_code2"],
            "department": mf["department"],
            "order_type": mf["order_type"],
            "operator_code": mf["operator_code"],
            "operate_time": mf["operate_time"],
            "extend_props":{
                "U9CID": mf['id'],
                "ALLDH": mf['oth_task_id']
            }
        }
        order_lines = []
        for index,itm in enumerate(tf):
            itm_lines =  {
            "item_code":itm['item_code'],
            "item_name":itm['item_name'],
            "batch_code":itm['batch_code'],
            "qty":itm['qty'],
            "request_id":itm["request_id"],
            "request_code":itm["request_code"],
            "request_itm":index +1,
            "source_bilid":itm["source_bilid"],
            "source_bilno":itm["source_bilno"],
            "source_bilitm":index + 1,
                "extend_props" : {
                "U9CID": str(itm['id']),
                "U9SOURCEID": itm['u9sourceid'],
                "U9SOURCENO": itm['u9sourceno'],
                "U9PROJECTID": itm['u9projectid'],
                "U9PROJECTNM": itm['u9projectnm'],
                }
             }
            order_lines.append(itm_lines)
        addData = {}
        addData['transfer_order'] = transfer_order
        addData['order_lines'] = order_lines
        return addData